import React, { useState, useEffect } from 'react'

import './style.css'


const AMap = window.AMap
// const AMapUI = window.AMapUI

const TYPE_TABS = [
  {
    name: '公交',
    icon: "http://res.lexiangpingou.cn//myfiles/2021-09-24/oyYnkb6LlKnW6mRtHpIV5rPs5iXLraFVGoUzGTfK.png",
    value: '公交|公交站|地铁站|动车站|轻轨站',
    subValue: '',
    markerIcon: 'http://res.sihai0577.com//myfiles/2021-11-13/ZenOtEfaF5ULdDixvLbpIgIHv9yARYLoVlXnFKt5.png'
  },
  {
    name: '学校',
    icon: "http://res.lexiangpingou.cn//myfiles/2021-09-24/kUCnnl2QOnnvCA9lQeTsg7JPYz4CBUgGuh4jKNCd.png",
    value: '学校',
    subValue: '',
    markerIcon: 'http://res.sihai0577.com//myfiles/2021-11-13/HpxUv89dLO7POQcn4Hhj30BlT3jU4IJQJr2XEAWH.png'
  },
  {
    name: '餐饮',
    icon: "http://res.lexiangpingou.cn//myfiles/2021-09-24/6fLvtGsXd7x6GWbhCAqlpwPgwOtE6ATmxsJxmzsO.png",
    value: '餐饮服务|餐饮|美食|奶茶',
    subValue: '',
    markerIcon: 'http://res.sihai0577.com//myfiles/2021-11-13/dHmi0MWje4yDK62UdvgBilr6kRUSW7E8bdb08CUj.png'
  },
  {
    name: '购物',
    icon: "http://res.lexiangpingou.cn//myfiles/2021-09-24/aC2lbyx9bwV7EFFmk7mNjvdjZx3qnZMjoZaEpHiF.png",
    value: '商城|购物服务|购物',
    subValue: '',
    markerIcon: 'http://res.sihai0577.com//myfiles/2021-11-13/e7otVO35iInCtyu6ln9p3LqBcIivXrA6h3RTsTrB.png'
  },
  {
    name: '医院',
    icon: "http://res.lexiangpingou.cn//myfiles/2021-09-24/F9tY3XCWlPLWZalEqoWmxU4jqnx7tqrGKGiol4wH.png",
    value: '医疗保健服务|医院',
    subValue: '',
    markerIcon: 'http://res.sihai0577.com//myfiles/2021-11-13/qFpUByOQSXDytp0UByCWQiZczTHPhebURo4SEMjU.png'
  },
]

let map = null
let _placeSearch = null
let num = 0
export default function NearbyAmenities({ lat, lng }) {
  const center = [lng, lat]
  const [nearByList, setNearByList] = useState([])
  const [currentType, setCurrentType] = useState(TYPE_TABS[0])
  const [placeSearchConfig, setPlaceSearchConfig] = useState({
    type: currentType.value, // 兴趣点类别
    pageSize: 20, // 单页显示结果条数
    pageIndex: 1, // 页码
    citylimit: false,  //是否强制限制在设置的城市内搜索
    // panel: "panel", // 结果列表将在此容器中进行展示。
    autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
    showCover: false, // 在使用map属性时，是否在地图上显示周边搜索的圆或者范围搜索的多边形，默认为true
  })

  // console.log(nearByList, placeSearchConfig.type)

  useEffect(() => {
    map && searchNearby(map, placeSearchConfig)
  }, [placeSearchConfig])


  useEffect(() => {
    if (nearByList?.pois?.length > 0 && map) {
      let data = nearByList.pois

      map.clearMap();

      for (let i = 0; i < data.length; i++) {
        const location = data[i].location
        let marker = new AMap.Marker({
          icon: currentType.markerIcon,
          position: [location.lng, location.lat],
          title: i
        });
        map.add(marker)
      }

    }
  }, [nearByList])


  useEffect(() => {
    map = new AMap.Map('map-wrapper', {
      zoom: 17,
      scrollWheel: false,
      resizeEnable: true,
      center: center,
    })
    searchNearby(map, placeSearchConfig)
    return () => {
      map = null
    }
  }, [])

  return (
    <>
      <div id='map-wrapper'>
      </div>
      <div id="nearByList">
        <div className="top flex-row">
          {
            TYPE_TABS.map((item, i) => (
              <img key={i + item.icon} src={item.icon} alt="" className="icon" onClick={() => {
                setCurrentType(item)
                setPlaceSearchConfig({ ...placeSearchConfig, type: item.value })
              }} />
            ))
          }
        </div>
        <div className="title">
          附近{currentType.name}
        </div>

        <div className="list" id="list">
          {nearByList?.pois &&
            nearByList.pois?.map(item => (
              <div className="list-item flex-row" key={item.id} onClick={() => {
                map.setZoomAndCenter(20, [item.location.lng, item.location.lat])
                let marker = new AMap.Text({
                  position: [item.location.lng, item.location.lat],
                  text: `<div class="marker-text">${item.name}</div>`
                });
                map.add(marker)
              }}>
                <div className="left flex-column">
                  <div className="item-title">
                    {item.name}
                  </div>
                  <div className="item-address">
                    {item.address}
                  </div>
                </div>
                <div className="right">
                  约{item.distance}m
                </div>
              </div>
            ))
          }

          {
            nearByList?.length === 0 && <div className="nodata">
              没有找到附近的{currentType.name}
            </div>
          }
        </div>
      </div>
    </>
  )

  function searchNearby(_map, searchConfig) {
    let placeSearch = null


    AMap.service(["AMap.PlaceSearch"], function () {
      //构造地点查询类
      placeSearch = new AMap.PlaceSearch({
        map: _map, // 展现结果的地图实例
        ...searchConfig
      });

      _placeSearch = placeSearch
      placeSearch.searchNearBy(currentType.subValue, center, 400, function (status, res) {
        if (status === 'complete') {
          if (res?.info === 'OK') {
            setNearByList(res.poiList)
          }
        } else if (status === 'no_data') {
          setNearByList([])
        } else {
          console.log('其他错误', 'status', status, 'res', res)
        }
      });

    });
    return placeSearch
  }
}
